import SparkMD5 from 'spark-md5';
export function blobToBase64(blob) {
    return new Promise((resolve) => {
        const reader = new FileReader()
        reader.onload = function () {
            const base64String = reader.result.split(',')[1] // 去掉前缀
            resolve(base64String)
        }
        reader.readAsDataURL(blob)
    })
}

export function dataURLtoBlob(params) {
    return new Promise((resolve, reject) => {
        const { dataURL, type, quality } = params
        const arr = dataURL.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        resolve(new Blob([u8arr], { type }))
    })
}

export function calculateFileMD5(file) {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        const spark = new SparkMD5.ArrayBuffer();

        fileReader.onload = function (e) {
            spark.append(e.target.result);
            resolve(spark.end());
        };

        fileReader.onerror = function (err) {
            reject(err);
        };

        fileReader.readAsArrayBuffer(file);
    });
}
export function getObjectURL(file) {
    let url
    if (window["createObjectURL"] != undefined) {
        // basic
        url = window["createObjectURL"](file)
    } else if (window.URL != undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file)
    }
    return url
}
